package com.rzjm.api.netty.water;

import com.rzjm.api.netty.water.business.inhandler.DispatchHandler;
import com.rzjm.api.service.IDeviceWaterMessagesService;
import com.rzjm.api.service.IDeviceWaterService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Component
public class MessageHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(MessageHandler.class);
    private static IDeviceWaterService devicesService;
    private static IDeviceWaterMessagesService deviceMessagesService;
//    private static IDeviceOnOffLinesService deviceOnOffLinesService;
    private static DispatchHandler dispatchHandler;

    @Autowired
    public void setDispatchHandler(DispatchHandler dispatchHandler) {
        MessageHandler.dispatchHandler = dispatchHandler;
    }
    @Autowired
    public void setDevicesService(IDeviceWaterService devicesService) {
        MessageHandler.devicesService = devicesService;
    }
    @Autowired
    public void setDeviceMessagesService(IDeviceWaterMessagesService deviceMessagesService) {
        MessageHandler.deviceMessagesService = deviceMessagesService;
    }
//    @Autowired
//    public void setDeviceOnOffLinesService(IDeviceOnOffLinesService deviceOnOffLinesService) {
//        MessageHandler.deviceOnOffLinesService = deviceOnOffLinesService;
//    }

    public static void messageHandler(ChannelHandlerContext ctx, String message) {
        try {
            String channelId = ctx.channel().id().asLongText();
            ctx.channel().attr(AttributeKey.valueOf("lastDate")).set(new Date());
            LOGGER.info("=======>设备上报数据，解析前数据 message={} channel={} time = {}", message, channelId,  LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//            System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) +": 上报数据，解析前数据 : " + message);
            message = analysisMessage(message);
            LOGGER.info("=======>设备上报数据，解析后数据 message={}", message);
//            System.out.println("设备上报数据，解析后数据 : " + message);
            if (StringUtils.isNotEmpty(message)) {
//                messageHandlerInternal(ctx, message);
                dispatchHandler.dispatchMsg(ctx, message);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("上报信息处理发生异常", e);
        }
    }


    /**
     * 解析完整Json报文
     * 防止设备上报的数据为不完整或者多余数据的Json
     * 例如 【"id":13,"type":1}】=》不完整报文直接丢弃
     * 【{"type":1{"id":13,"type":1}】=》丢弃【"type":1}】保留【{"id":13,"type":1}】
     * DelimiterBasedFrameDecoder用【}】分割成多个报文接收，也就是说接收报文只有一个【}】且在字符串最后。
     *
     * @param message 原始报文
     * @return 解析出来的完整报文
     */
    private static String analysisMessage(String message) {
        if (StringUtils.isEmpty(message)) {
            return null;
        }
        int start = message.lastIndexOf("{");
        if (start < 0) {
            LOGGER.error("丢弃报文，报文没有开始字符【{】，message：{}", message);
            return null;
        }
        return message.substring(start);
    }


}
